<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2020/1/13
 * Time: 11:14
 */

require_once '../../lib/start.php';

$urlTemplate = 'https://www.ali213.net/news/html/2020-1/481711_11.html';

$day = 12;

try {
    $crawler = $client->request('GET', $urlTemplate);
    $str = $crawler->filter('#Content')->text();

    $headStr = 'exptime|';
    $footerStr = '\'.split(\'|\'),0,{}';
    $retStr = getBetweenStr($str,$headStr,$footerStr);
    $retArr = explode('|',$retStr);

    $url = $retArr[4].'://'.$retArr[5].'.'.$retArr[2].'.'.$retArr[1].'/'.$retArr[8].'/'.$retArr[9].'/'.$retArr[10].'/'.$retArr[7].'/%s/%s.jpg';
    $resArr = getImgUrl($retArr,$url,$day);
    $urlsRes = array_unique($resArr);

    foreach ($urlsRes as $k=>&$urlItem){
        try{
            $response = $httpClient->get($urlItem);
        }catch (\Exception $e){
            $urlExp = explode('/',$urlItem);
            $urlExp[7] = $urlExp[7] + 1;
            $urlItem = implode('/',$urlExp);
            try{
                $response2 = $httpClient->get($urlItem);
            }catch (\Exception $e){
                unset($urlItem[$k]);
            }
        }
    }
    unset($urlItem);

    $insert['title'] = $insert['name'] = $crawler->filter('body > div.ns_t4 > h1')->text();
    $insert['img_num'] = count($urlsRes);
    $insert['img_src'] = implode(',',$urlsRes);
    $insert['create_time'] = date('Y-m-d H:i:s');
    $db->insert('girls_img',$insert);
    var_dump($db->log());
} catch (Exception $e) {
    var_dump($e);
}


/**
 * e.g. https://img2.ali213.net/picfile/News/2020/01/12/584_20200112114607818.jpg
 * @param $retArr
 * @param $url
 * @param $day
 * @return array
 */
function getImgUrl($retArr,$url,$day){
    $resArr = [];
    foreach ($retArr as $item){
        if (preg_match('/\d_\d/',$item) === 1){
            $resArr[] = sprintf($url,$day,$item);
        }
    }
    return $resArr;
}